package com.vrv.common.utils;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.util.Log;

public class FileUtils {

    /**
     * 根据网络URL来获取输入流
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static InputStream getImageStream(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        return conn.getInputStream();
    }

    /**
     * 获得文件后缀名
     *
     * @param fileName
     * @return
     */
    @SuppressLint("DefaultLocale")
    public static String getFilePostfix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }

    /**
     * 将流写到本地磁盘
     *
     * @param localpath
     * @param url
     */
    public static void download(String localpath, String url) {
        InputStream inputStream = null;
        try {

            inputStream = getImageStream(url);

            if (inputStream == null)
                return;

            File file = new File(localpath);
            if (file.getParentFile().exists()) {
                write2SDCard(inputStream, file);
            } else {
                file.getParentFile().mkdirs();
                write2SDCard(inputStream, file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断当前的sdcard可否使用
     *
     * @return
     */
    public static boolean hasSDcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * 把文件写入SD卡
     *
     * @param file
     */
    public static void write2SDCard(InputStream inputStream, File file) {
        /*
         * 向SD卡中写入文件,用Handle传递线程
         */
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int currentReadLength = inputStream.read(buffer);
            while (currentReadLength != -1) {
                outputStream.write(buffer, 0, currentReadLength);
                currentReadLength = inputStream.read(buffer);
                if (currentReadLength == -1) {
                    outputStream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用文件的byte[]数据，把文件写到本地。
     *
     * @param bFile
     *            ：文件的byte[]数据
     * @return
     */
    public static boolean saveFile(byte[] bFile, String fileWritePath) {
        FileOutputStream out = null;
        try {
            File fileWriter = new File(fileWritePath);
            if (!fileWriter.getParentFile().exists()) {
                fileWriter.mkdirs();
            }
            out = new FileOutputStream(fileWriter);
            out.write(bFile);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            close(out);
        }
    }

    /**
     * 关闭文件流
     *
     * @param stream
     */
    public static void close(Closeable stream) {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在SD卡上创建文件
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public static File createSDFile(String path, String fileName) throws IOException {
        if (path != null) {
            path = getProjectPath() + path + "/";
        } else {
            path = getProjectPath();
        }
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File file = new File(path + fileName);
        if (!file.exists()) {
            dir.createNewFile();
        }
        return file;
    }

    /**
     * 获取项目文件夹在SD卡中的路径
     *
     * @return
     */
    public static String getProjectPath() {
        String projectPath = getSDCardAbsolutePath() + "app" + "/";
        createPath(projectPath);
        return projectPath;
    }

    /**
     * 清理缓存
     */
    public static boolean clearTemp() {
        try {
            deleteDirectory(new File(getProjectPath()));
        } catch (Exception e) {
            Log.i("清空缓存出错", e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * Deletes a directory recursively.
     *
     * @param directory
     *            directory to delete
     * @throws IOException
     *             in case deletion is unsuccessful
     */
    public static void deleteDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            return;
        }

        if (!isSymlink(directory)) {
            cleanDirectory(directory);
        }

        if (!directory.delete()) {
            String message = "Unable to delete directory " + directory + ".";
            Log.i("删除目录", message);
            throw new IOException(message);
        }
    }

    /**
     * Determines whether the specified file is a Symbolic Link rather than an
     * actual file.
     * <p>
     * Will not return true if there is a Symbolic Link anywhere in the path,
     * only if the specific file is.
     * <p>
     * <b>Note:</b> the current implementation always returns {@code false} if
     * the system is detected as Windows using
     * {@link FilenameUtils#isSystemWindows()}
     *
     * @param file
     *            the file to check
     * @return true if the file is a Symbolic Link
     * @throws IOException
     *             if an IO error occurs while checking the file
     * @since 2.0
     */
    public static boolean isSymlink(File file) throws IOException {
        if (file == null) {
            throw new NullPointerException("File must not be null");
        }
        if (File.separatorChar == '\\') {
            return false;
        }
        File fileInCanonicalDir = null;
        if (file.getParent() == null) {
            fileInCanonicalDir = file;
        } else {
            File canonicalDir = file.getParentFile().getCanonicalFile();
            fileInCanonicalDir = new File(canonicalDir, file.getName());
        }

        if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Cleans a directory without deleting it.
     *
     * @param directory
     *            directory to clean
     * @throws IOException
     *             in case cleaning is unsuccessful
     */
    public static void cleanDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            String message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (!directory.isDirectory()) {
            String message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        }

        File[] files = directory.listFiles();
        if (files == null) { // null if security restricted
            throw new IOException("Failed to list contents of " + directory);
        }

        IOException exception = null;
        for (File file : files) {
            try {
                forceDelete(file);
            } catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception) {
            throw exception;
        }
    }

    /**
     * Deletes a file. If file is a directory, delete it and all
     * sub-directories.
     * <p>
     * The difference between File.delete() and this method are:
     * <ul>
     * <li>A directory to be deleted does not have to be empty.</li>
     * <li>You get exceptions when a file or directory cannot be deleted.
     * (java.io.File methods returns a boolean)</li>
     * </ul>
     *
     * @param file
     *            file or directory to delete, must not be {@code null}
     * @throws NullPointerException
     *             if the directory is {@code null}
     * @throws FileNotFoundException
     *             if the file was not found
     * @throws IOException
     *             in case deletion is unsuccessful
     */
    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectory(file);
        } else {
            boolean filePresent = file.exists();
            if (!file.delete()) {
                if (!filePresent) {
                    // throw new FileNotFoundException("File does not exist: " +
                    // file);
                    Log.e("删除文件", "File does not exist: " + file);
                }
                String message = "Unable to delete file: " + file;
                throw new IOException(message);
            }
        }
    }

    /**
     * 获取文件夹下的所有文件
     *
     * @param path
     * @param filter
     * @return
     */
    public static File[] getAllFiles(String path, FilenameFilter filter) {
        File[] files = null;
        if (!StringUtils.isNullOrEmpty(path)) {
            files = new File(path).listFiles(filter);
        }

        return files;
    }

    /**
     * 判断文件夹下是否有指定的文件
     *
     * @param path
     * @param filter
     * @return
     */
    public static boolean hasFile(String path, FilenameFilter filter) {
        File[] files = getAllFiles(path, filter);
        if (files != null && files.length > 0) {
            return true;
        }
        return false;
    }

    /**
     * 获得SD卡根目录路径
     *
     * @return String类型 SD卡根目录路径
     */
    public static String getSDCardAbsolutePath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    }

    /**
     * 读取文件
     *
     * @param fileName
     *            文件名，与当前类在同一目录
     * @return
     */
    public static byte[] readSDCardProjectFile(String fileName) {
        // return readFile(getSdCardAbsolutePath() + "/" + fileName);
        return readFile(getProjectPath() + fileName);
    }

    /**
     * 读取文件
     *
     * @param fileName
     *            文件名，与当前类在同一目录
     * @return
     */
    public static byte[] readFile(String fileName) {
        InputStream fin = null;
        byte[] buffer = null;
        try {
            fin = new FileInputStream(new File(fileName));
            buffer = new byte[fin.available()];
            fin.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }

    public static byte[] readAbsolutePathFile(String path) {
        InputStream fin = null;
        byte[] buffer = null;
        try {
            fin = new FileInputStream(new File(path));
            buffer = new byte[fin.available()];
            fin.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }

    /**
     * 创建目录
     */
    public static void createPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
    }
}
